<template>
  <div class="app-container">
    <div class="bg-container">
      <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams">
        <el-form-item label="报告名称" prop="autoName">
          <el-input
              v-model="queryParams.autoName"
              clearable
              placeholder="请输入报告名称"
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              icon="Plus"
              plain
              type="primary"
              @click="handleAdd"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              :disabled="multiple"
              icon="Delete"
              plain
              type="danger"
              @click="handleDelete"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              icon="Download"
              plain
              type="warning"
              @click="handleExport"
          >导出
          </el-button>
        </el-col>

        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="autoReportLogList" @selection-change="handleSelectionChange" height="400px">
        <el-table-column align="center" type="selection" width="55"/>
        <el-table-column label="报告名称" prop="autoName"/>
        <el-table-column label="报告类型" prop="autoType">
          <template #default="scope">
            <el-tag v-if="scope.row.autoType == 0" type="success">一次性报告</el-tag>
            <el-tag v-else-if="scope.row.autoType == 1">周期性报告</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime">
          <template #default="scope">
            {{ parseTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="启用" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" :loading="scope.row.loading" active-text="正常" active-value="0"
                       inactive-text="关闭"
                       inactive-value="1" @click="handleChangeStatus(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作">
          <template #default="scope">
            <el-button icon="View" link plain
                       type="primary" @click="handleView(scope.row)">查看
            </el-button>
            <el-button icon="Fries" link plain
                       type="primary" @click="handleConfiguration(scope.row)">配置
            </el-button>
            <el-button icon="Edit" link plain
                       type="primary" @click="handleUpdate(scope.row)">编辑
            </el-button>
            <el-button icon="Delete" link plain
                       type="danger" @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          v-model:current-page="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[3, 5, 7, 10]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 20px; justify-content: flex-end"
          @size-change="getList"
          @current-change="getList"
      />
    </div>

    <!-- 添加或修改自动报告对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="600px">
      <el-form ref="autoReportLogRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="自动报告名称" prop="autoName">
          <el-input v-model="form.autoName" placeholder="请输入自动报告名称"/>
        </el-form-item>
        <el-form-item label="自动报告类型" prop="autoType">
          <el-select v-model="form.autoType" clearable filterable placeholder="请选择自动报告类型">
            <el-option label="一次性报告" :value="0"/>
            <el-option label="周期性报告" :value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="false" label="仪表盘" prop="dataScreenId">
          <el-input v-model="form.dataScreenId" placeholder="请输入仪表盘ID"/>
        </el-form-item>
        <el-form-item v-if="false" label="报告频率" prop="frequency">
          <el-select v-model="form.frequency" clearable filterable placeholder="请选择报告频率">
            <el-option label="每周" :value="0"/>
            <el-option label="每月" :value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="false" label="发送报告的星期几" prop="sendDayOfWeek">
          <el-select v-model="form.sendDayOfWeek" clearable filterable placeholder="请选择发送报告的星期几">
            <el-option :value="0" label="星期日"/>
            <el-option :value="1" label="星期一"/>
            <el-option :value="2" label="星期二"/>
            <el-option :value="3" label="星期三"/>
            <el-option :value="4" label="星期四"/>
            <el-option :value="5" label="星期五"/>
            <el-option :value="6" label="星期六"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="false" label="发送报告的每月几号" prop="sendDayOfMonth">
          <el-input-number v-model="form.sendDayOfMonth" :max="31" :min="1" placeholder="请输入发送报告的每月几号"/>
        </el-form-item>
        <el-form-item v-if="false" label="发送报告的小时" prop="sendHour">
          <el-input-number v-model="form.sendHour" :max="23" :min="0" placeholder="请输入发送报告的小时"/>
        </el-form-item>
        <el-form-item v-if="false" label="发送报告的分钟" prop="sendMinute">
          <el-input-number v-model="form.sendMinute" :max="59" :min="0" placeholder="请输入发送报告的分钟"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看自动报告信息 -->
    <el-dialog v-model="show" append-to-body title="查看自动报告信息" width="800px">
      <el-descriptions border>
        <el-descriptions-item label="自动报告ID">
          {{ form.id || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="自动报告名称">
          {{ form.autoName || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="自动报告类型">
          <el-tag v-if="form.autoType == 0" type="success">一次性报告</el-tag>
          <el-tag v-if="form.autoType == 1">周期性报告</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="启用状态">
          <el-tag v-if="form.status == 0" type="success">正常</el-tag>
          <el-tag v-if="form.status == 1" type="danger">关闭</el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="false" label="仪表盘ID">
          {{ form.dataScreenId || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="接收者列表">
          <el-table :data="form.recipients">
            <el-table-column label="接受者id" prop="userId"/>
            <el-table-column label="接收邮箱" prop="email"/>
            <el-table-column label="接收者名称" prop="name"/>
          </el-table>
        </el-descriptions-item>
        <el-descriptions-item label="报告频率">
          <el-tag v-if="form.frequency == 0" type="success">每周</el-tag>
          <el-tag v-if="form.frequency == 1">每月</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发送报告的星期几">
          <div v-if="form.sendDayOfWeek == 0">星期日</div>
          <div v-if="form.sendDayOfWeek == 1">星期一</div>
          <div v-if="form.sendDayOfWeek == 2">星期二</div>
          <div v-if="form.sendDayOfWeek == 3">星期三</div>
          <div v-if="form.sendDayOfWeek == 4">星期四</div>
          <div v-if="form.sendDayOfWeek == 5">星期五</div>
          <div v-if="form.sendDayOfWeek == 6">星期六</div>
        </el-descriptions-item>
        <el-descriptions-item label="发送报告的每月几号">
          {{ form.sendDayOfMonth || '--' }}号
        </el-descriptions-item>
        <el-descriptions-item label="发送报告的小时">
          {{ form.sendHour || '--' }}时
        </el-descriptions-item>
        <el-descriptions-item label="发送报告的分钟">
          {{ form.sendMinute || '--' }}分
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ parseTime(form.createTime) || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建者">
          {{ form.creator || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ parseTime(form.updateTime) || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="更新者">
          {{ form.updater || '--' }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelView">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="AutoLogInfo" setup>
import {getCurrentInstance, reactive, ref, toRefs} from "vue";
import {
  addAutoReportLog,
  delAutoReportLog,
  delAutoReportLogList,
  exportAutoReportLog,
  getAutoReportLog,
  listAutoReportLog,
  updateAutoReportLog,
  updateAutoReportLogStatus
} from "@/api/autoReportLog";
import router from "@/router";

const {proxy} = getCurrentInstance();

const autoReportLogList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const show = ref(false)

const form = reactive({
  autoName: '',
  status: "",
  autoType: "",
  frequency: ""
})

const data = reactive({
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    autoName: null,
    autoType: null,
    status: null,
    dataScreenId: null,
    frequency: null,
    sendDayOfWeek: null,
    sendDayOfMonth: null,
    sendHour: null,
    sendMinute: null,
  },
  rules: {
    autoName: [
      {required: true, message: "自动报告名称不能为空", trigger: ["blur", "change"]}
    ],
    autoType: [
      {required: true, message: "自动报告类型（0一次性报告 1--）不能为空", trigger: ["blur", "change"]}
    ],
    status: [
      {required: true, message: "启用状态（0正常 1关闭）不能为空", trigger: ["blur", "change"]}
    ],
    dataScreenId: [
      {required: true, message: "仪表盘ID不能为空", trigger: ["blur", "change"]}
    ],
    frequency: [
      {required: true, message: "报告频率（0表示每周，1表示每月）不能为空", trigger: ["blur", "change"]}
    ],
    sendDayOfWeek: [
      {required: true, message: "发送报告的星期几（0=星期天，1=星期一，...）不能为空", trigger: ["blur", "change"]}
    ],
    sendDayOfMonth: [
      {required: true, message: "发送报告的每月几号（1-31）不能为空", trigger: ["blur", "change"]}
    ],
    sendHour: [
      {required: true, message: "发送报告的小时不能为空", trigger: ["blur", "change"]}
    ],
    sendMinute: [
      {required: true, message: "发送报告的分钟不能为空", trigger: ["blur", "change"]}
    ],
  }
});

const {queryParams, rules} = toRefs(data);

// 查询自动报告数据列表
function getList() {
  loading.value = true;
  listAutoReportLog(queryParams.value).then(response => {
    autoReportLogList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  for (const key in form) {
    delete form[key];
  }
  form.status = 1;
  form.autoType = 1;
  form.frequency = 1;
  proxy.resetForm("autoReportLogRef");
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 新增按钮操作
function handleAdd() {
  Object.assign(form, {});
  open.value = true;
  title.value = "添加自动报告信息";
}

// 修改按钮操作
function handleUpdate(row) {
  const _cloneObj = JSON.parse(JSON.stringify(row));
  Object.assign(form, {});
  _cloneObj.autoType = Number(row.autoType);
  _cloneObj.status = Number(row.status);
  _cloneObj.frequency = Number(row.frequency);
  Object.assign(form, _cloneObj);
  open.value = true;
  title.value = "修改自动报告信息";
}

// 提交按钮
function submitForm() {
  proxy.$refs["autoReportLogRef"].validate(valid => {
    if (valid) {
      if (form.id != null) {
        updateAutoReportLog(form).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAutoReportLog(form).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 删除按钮操作
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除自动报告信息"' + row.id + '"的数据项？').then(function () {
    return delAutoReportLog({id: row.id});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

// 批量删除按钮操作
function handleDeleteList() {
  const idList = ids.value;
  proxy.$modal.confirm('是否确认删除自动报告信息"' + idList + '"的数据项？').then(function () {
    return delAutoReportLogList({ids: idList.join(',')});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

// 导出按钮操作
function handleExport() {
  exportAutoReportLog(queryParams.value)
}

// 查看自动报告信息操作
function handleView(row) {
  const _cloneObj = JSON.parse(JSON.stringify(row));
  Object.assign(form, {});
  _cloneObj.autoType = Number(row.autoType);
  _cloneObj.status = Number(row.status);
  _cloneObj.frequency = Number(row.frequency);
  Object.assign(form, _cloneObj);
  show.value = true;
}

// 取消查看自动报告信息
function cancelView() {
  show.value = false;
  reset();
}

// 开关自动报告信息操作
function handleChangeStatus(row) {
  row.loading = true;
  const id = row.id
  getAutoReportLog({id: id}).then(response => {
    let item = response.data;
    if (item.status === '1') {
      item.status = '0';
    } else if (item.status === '0') {
      item.status = '1';
    }
    updateAutoReportLogStatus(item).then(res => {
      if (res.data) {
        proxy.$modal.msgSuccess("修改成功");
        getList();
      }
    }).finally(() => {
      row.loading = false;
    });
  })
}

// 配置自动报告
function handleConfiguration(row) {
  router.push({path: '/autoLog/configuration', query: {id: row.id}})
}

getList();
</script>